<template>
  <div>
    <Window @close="close" @confirm="publishBlog">
      <!-- 内容部分 -->
      <div class="main">
        <el-button class="btn" type="primary" @click="blogConfig.show = true">
          <setting style="width: 1em; height: 1em" />
          <span>&nbsp;详情设置</span>
        </el-button>
        <el-form :model="blogFormData" :rules="rules" ref="blogFormRef">
          <el-form-item prop="title">
            <div style="width: 100%">
              <el-input
                placeholder="请输入博客标题"
                v-model="blogFormData.title"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="content">
            <div :style="{ width: '100%' }">
              <EditorHtml
                v-model="blogFormData.content"
                v-if="blogFormData.editorType == 0"
              ></EditorHtml>
              <EditorMarkdown
                v-else
                v-model="blogFormData.markdownContent"
                @htmlContent="setHtmlContent"
              ></EditorMarkdown>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 新增、修改博客设置对话框 -->
      <el-dialog
        v-model="blogConfig.show"
        :title="dialogTitle"
        @closed="blogConfig.show = false"
        draggable
        width="50%"
      >
        <el-form
          :model="blogFormData"
          label-position="top"
          :rules="rules"
          ref="blogFormRef"
        >
          <el-form-item label="博客分类" prop="categoryId">
            <el-select
              v-model="blogFormData.categoryId"
              clearable
              placeholder="请选择分类"
              :style="{ width: '100%' }"
            >
              <el-option :value="0" label="全部分类"></el-option>
              <el-option
                :value="item.categoryId"
                :label="item.categoryName"
                v-for="item in categoryList"
                :key="item.categoryId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="封面" prop="cover">
            <CoverUpload v-model="blogFormData.cover"></CoverUpload>
          </el-form-item>
          <el-form-item label="博客类型" prop="type">
            <el-radio-group v-model="blogFormData.type">
              <el-radio :label="0">原创</el-radio>
              <el-radio :label="1">转载</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="原文地址"
            prop="reprintUrl"
            v-if="blogFormData.type == 1"
          >
            <el-input
              v-model="blogFormData.reprintUrl"
              placeholder="请输入原文地址"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="评论" prop="allowComment">
            <div class="allow-comment">
              <el-radio-group v-model="blogFormData.allowComment">
                <el-radio :label="1">允许</el-radio>
                <el-radio :label="0">不允许</el-radio>
              </el-radio-group>
              <span class="info"
                >请先在评论设置里设置好相应参数，评论才会生效</span
              >
            </div>
          </el-form-item>
          <el-form-item label="博客摘要" prop="summary">
            <el-input
              type="textarea"
              rows="3"
              :autosize="{ minRows: 2, maxRows: 4 }"
              v-model="blogFormData.summary"
            />
          </el-form-item>
          <el-form-item label="博客标签" prop="categoryDesc">
            <div class="tag-input-panel">
              <div class="tag-list">
                <el-tag
                  v-for="(item, index) in blogFormData.tag"
                  @close="closeTag(index)"
                  closable
                  class="tag-item"
                  :key="index"
                >
                  {{ item }}
                </el-tag>
              </div>
              <span class="info" v-if="blogFormData.tag.length == 0"
                >添加标签更容易被搜索引擎收录</span
              >
              <el-input
                class="tag-input"
                v-if="showTagInput"
                v-model="tagInputValue"
                size="small"
                @blur="tagInputResult"
                @keyup.enter="tagInputResult"
              >
              </el-input>
              <el-button v-else size="small" @click="showTagInputHandler">
                + New Tag
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </Window>
  </div>
</template>

<script setup>
import {
  ref,
  getCurrentInstance,
  reactive,
  nextTick,
  onUnmounted,
} from "vue";
const { proxy } = getCurrentInstance();

// 博客正文
const blogFormRef = ref(null);
const blogFormData = ref({ tag: [] });

// 组件初始化
const init = (type, data) => {
  blogConfig.show = true;
  getCategory();
  startTimer();
  nextTick(() => {
    proxy.$refs.blogFormRef.resetFields();
    blogFormData.value = { tag: [] };
    if (type == "add") {
      dialogTitle.value = "新增博客";
      getUserInfo();
    } else {
      dialogTitle.value = "修改博客";
      getBlogDetail(data.blogId);
    }
  });
};

// 暴露init
defineExpose({ init });

// 关闭窗口
const emit = defineEmits();
const close = () => {
  blogConfig.show = false;
  emit("close");
};

// 清除定时器
onUnmounted(() => {
  cleanTimer();
});

// 获取用户数据
const getUserInfo = async () => {
  let result = await proxy.Request({
    url: "/getUserInfo",
  });
  if (!result) {
    return;
  }
  blogFormData.value.editorType = result.data.editorType;
};

// 对话框标题
let dialogTitle = ref();

// 窗口设置
const blogConfig = reactive({
  show: false,
});

// 表单校验规则
const rules = {
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入正文" }],
  categoryId: [{ required: true, message: "请选择博客分类" }],
  type: [{ required: true, message: "请选择博客类型" }],
  allowComment: [{ required: true, message: "请选择是否允许评论" }],
  reprintUrl: [{ required: true, message: "请输入原文地址" }],
};

// 博客分类
const categoryList = ref([]);
const getCategory = async () => {
  let result = await proxy.Request({
    url: "/category/loadAllCategory4Blog",
  });
  if (!result) {
    result;
  }
  categoryList.value = result.data;
};

// markdown编辑器设置编辑器html内容
const setHtmlContent = (htmlContent) => {
  blogFormData.value.content = htmlContent;
};

// 自动保存
const autoSave = async () => {
  if (
    blogFormData.value.title == undefined ||
    blogFormData.value.content == undefined ||
    timmer.value == null ||
    blogConfig.show
  ) {
    return;
  }
  const params = {};
  Object.assign(params, blogFormData.value);
  let result = await proxy.Request({
    url: "/blog/autoSaveBlog",
    params: params,
  });
  if (!result) {
    return;
  }
  blogFormData.value.blogId = result.data;
};

// 自动保存定时器
let timmer = ref(null);
const startTimer = () => {
  timmer.value = setInterval(() => {
    autoSave();
  }, 1000);
};
const cleanTimer = () => {
  if (timmer.value !== null) {
    clearInterval(timmer.value);
    timmer.value = null;
  }
};

// 标签相关
//是否显示tag输入框
const showTagInput = ref(false);
// 点击加号显示tag输入框
const showTagInputHandler = () => {
  showTagInput.value = true;
};
//tag输入框的值
const tagInputValue = ref(null);
// 添加tag
const tagInputResult = (e) => {
  if (tagInputValue.value == undefined) {
    return;
  }
  showTagInput.value = false;
  if (blogFormData.value.tag.indexOf(tagInputValue.value.trim()) == -1) {
    blogFormData.value.tag.push(tagInputValue.value.trim());
  }
  tagInputValue.value = undefined;
};

// 获取博客详情
const getBlogDetail = async (blogId) => {
  let result = await proxy.Request({
    url: "/blog/getBlogById",
    params: {
      blogId: blogId,
    },
  });
  if (!result) {
    proxy.$message.error("获取博客详情失败");
    return;
  }

  blogFormData.value = result.data;
  if (result.data.tag) {
    blogFormData.value.tag = result.data.tag.split("|");
  } else {
    blogFormData.value.tag = [];
  }
};

// 发布博客
const publishBlog = () => {
  proxy.$refs.blogFormRef.validate(async (valid) => {
    if (!valid) {
      proxy.$message.error("请完善博客信息");
      return;
    }
    const params = {};
    Object.assign(params, blogFormData.value);
    params.tag = params.tag.join("|");
    let result = await proxy.Request({
      url: "/blog/saveBlog",
      params,
    });
    if (!result) {
      proxy.$message.error("发布失败");
      return;
    }
    proxy.$message.success(`${dialogTitle.value}成功`);
    blogConfig.show = false;
    emit("close");
  });
};
</script>

<style lang="scss" scoped>
.main {
  margin: 10px 0;
  width: 100%;
  height: calc(100vh - 234px);

  .btn {
    position: absolute;
    left: 76px;
    top: 20px;
  }
}
.allow-comment {
  display: flex;

  .info {
    margin-left: 20px;
    display: flex;
    height: 34px;
    line-height: 34px;
    opacity: 0.7;
  }
}

.tag-input-panel {
  height: 48px;
  display: flex;
  flex-wrap: wrap;

  .tag-list,
  .info,
  .tag-input {
    margin-right: 5px;
    height: 24px;
    line-height: 24px;
  }

  .tag-item {
    margin-right: 5px;
  }

  .info{
    opacity: 0.7;
  }

  .tag-input {
    width: 80px;
  }
}
</style>